package com.stars.easyms.demo.rest.service.redis;

import com.stars.easyms.redis.lock.DistributedLock;
import com.stars.easyms.rest.RestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class EasyMsRedisDemo2Service implements RestService<Void, Void> {

    @Override
    public Void execute(Void input) {
        DistributedLock distributedLock = new DistributedLock("test");
        new Thread(() -> {
            if (distributedLock.lock()) {
                System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis() + ": 获取到分布式锁!");
                try {
                    Thread.sleep(10000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis() + ": 释放分布式锁!");
                    distributedLock.unlock();
                }
            }
        }).start();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                if (distributedLock.lock()) {
                    System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis() + ": 获取到分布式锁!");
                    try {
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis() + ": 释放分布式锁!");
                        distributedLock.unlock();
                    }
                }
            }).start();
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}